import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  TextInput,
  Dimensions,
  StyleSheet,
  ListView,
  Platform,
  NativeAppEventEmitter,
  DeviceEventEmitter,
} from 'react-native';

import _ from 'lodash';
import styles from './indexStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';

import api from '../../services/api';
import LoadingTip from '../global/LoadingTip';
import Touch from '../global/Touch';
// import Kohana from '../global/textinputEffects/Kohana';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class SearchList extends Component {
    constructor(props) {
		super(props);

        this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
		this.state = {
			currentPage: 1,
            noData: false,
            pagesize: 10,
            showLoading: false,
            search: '',
            dataSource: this.ds.cloneWithRows([]),
		};

        this.list = [];
        this.totalpage = 0;

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount() {
        // this.onLoad();
	}

    // _onNavigatorEvent(event){
    //     // console.log("$$$", event);
    //
    //     if (event.type === 'ScreenChangedEvent') {
	// 		if (event.id === 'didAppear') { //出现时
    //             this.onLoad();
	// 		}
	// 	}
    // }

    onLoad(search){
        this.setState({ showLoading: true,noData: false,});
        this._retrieveList(search);
    }

    async _retrieveList(search) {
        let list;
        // let {search} = this.state;
        list = await api.post('/housekeeper/searchlist',{search: encodeURIComponent(search)});
        if(list && list.data){
            this._endList(list.data);
        }else {
            this.setState({noData: true, showLoading: false});
        }

    }

    _endList(list){

        // console.log("$$$$$$$", list);
        this.list = list;

        if(!this.list || this.list.length==0){
            this.setState({noData: true, showLoading: false});
            return;
        }

        this.setState({
            dataSource: this.ds.cloneWithRows(list)
        });

        this.setState({ showLoading: false,});

    }

    _fireMessage(data){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        Emitter.emit('click_message', data);
    }

    _renderRow(rowData, sectionID, rowID){
        return (
            <Touch onPress={this._fireMessage.bind(this, rowData)}>
                <View style={{marginLeft:15,paddingTop:15,paddingBottom:15,flexDirection: 'row',alignItems:'center',borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                        <View style={styles.headImageContainer}>
                            <Image source={{uri:rowData.wxHeader}} style={styles.headImage}/>
                        </View>
                    <View style={{flex:1, marginLeft:10}}>
                        <Text style={{fontSize: 15, color: '#555555',}}>{decodeURIComponent(rowData.wxName)}</Text>
                        <Text style={{fontSize: 13, color: '#7B7B7B', marginTop: 6, }}>{rowData.homeAddress}</Text>
                    </View>
                </View>
            </Touch>
        );
    }

    _renderNodata(){
        return (
            <View style={styles.noDataContent}>
                <Image source={require('../../../img/hk_no_data.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>没有找到您输入的内容</Text>
            </View>
        );
    }

    _clearAction(){
        this.props.navigator.pop();
    }

    render() {
        return (
            <View style={{height:deviceHeight, width: deviceWidth, position:'absolute', backgroundColor:"#f3f3f3"}}>
                <View style={styles.searchContainer}>
                    <View style={styles.searchInputContainer}>
                        <Image source={require('../../../img/search_icon.png')} />
                        <TextInput
                            style={styles.textInput}
                            editable = {true}
                            onChangeText={(text)=>{
                                this.setState({search:text});
                                if(text){
                                    this.onLoad(text);
                                }
                            }}
                            clearButtonMode={'while-editing'}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入姓名或房间号'}
                            placeholderTextColor={'#B5B5B5'}
                        />
                    </View>
                    <TouchableOpacity onPress={this._clearAction.bind(this)}>
                        <Text style={styles.addressBtnText}>取消</Text>
                    </TouchableOpacity>
                </View>
                {this.state.noData?this._renderNodata():
                <ListView
                    enableEmptySections={true}
                    contentStyle={{backgroundColor:"#f3f3f3"}}
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow.bind(this)}
                />}
                <LoadingTip show={this.state.showLoading}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
SearchList = connectHelper(state => state)(SearchList);

module.exports = SearchList;
